//
//  Const.swift
//
//  Created by ios on 2023/2/27.
//

import Foundation
import UIKit
@_exported import MXCommonModule


public let DeviceDirectionLandscapeScreenNotice: NSNotification.Name = NSNotification.Name.init("GRDeviceDirectionLandscapeScreenNotice")
public let DeviceDirectionPortraitScreenNotice: NSNotification.Name = NSNotification.Name.init("GRDeviceDirectionPortraitScreenNotice")

private let AppPackageNameEncipher: String = "b3V0LWkzMS1tajYw"
public var AppPackageName: String{
    return String.init(base64: AppPackageNameEncipher) ?? ""
}

public var AppVersionName: String = "1"

public var PrivacyPolicy = "https://be.berrly.xyz/x/XGamesLive/privacy-policy.html"
public var Terms = "https://be.berrly.xyz/x/XGamesLive/terms-of-use.html"

public var AppversionCodeStr: String {
    let infoDictionary = Bundle.main.infoDictionary!
    let minorVersion = infoDictionary["CFBundleShortVersionString"]
    let appVersion = minorVersion as! String
    return appVersion
}

let DeviceType: String = "2"

let AppleID = "6466620239"

var currentLanguage: String{
    let languages: [String] = UserDefaults.standard.object(forKey: "AppleLanguages") as! [String]
    let currentLanguage = languages.first
    return currentLanguage ?? "zh-Hans-CN"
}

var currentTimeStamp: String{
    let date = Date()
    let zone = TimeZone.current
    let interval = zone.secondsFromGMT(for: date)
    return (interval / 3600).description
}

func convertDate(time: String)->String{
    if let date = time.stringToDate()?.getOriginalDateFromatAnDate() {
        let timeInterval = abs(NSInteger(date.timeIntervalSince(Date())))
        if timeInterval < 24 * 60 * 60{
            if timeInterval < 60{
                return "\(timeInterval) s ago"
            }else if timeInterval < 3600{
                return "\(timeInterval / 60) m ago"
            }
            return "\(timeInterval / 3600) h ago"
        }else if timeInterval < 24 * 60 * 60 * 7{
            return "\(timeInterval / (24 * 60 * 60)) days ago"
        }else if timeInterval < 24 * 60 * 60 * 30{
            return "\(timeInterval / (24 * 60 * 60 * 7)) weeks ago"
        }
        return date.toFormat("MM-dd")
    }
    return ""
}

func imageWithName(_ name: String)-> UIImage{
    return UIImage(named: name) ?? UIImage()
}

//MARK: Forced landscape
func rotateScreenLandscape (scapeType: UIInterfaceOrientationMask = .landscapeRight,orientation: UIInterfaceOrientation = .portrait) {
    guard let appDelegate: AppDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return
    }
    appDelegate.scapeType = scapeType
    let resetOrientationTargert = NSNumber(integerLiteral: UIInterfaceOrientation.unknown.rawValue)
    UIDevice.current.setValue(resetOrientationTargert, forKey: "orientation")
    
    let orientationTarget = NSNumber(integerLiteral: orientation.rawValue)
    UIDevice.current.setValue(orientationTarget, forKey: "orientation")
    
}
//MARK: Forced portrait
func rotateScreenPortrait() {
    guard let appDelegate: AppDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return
    }
    appDelegate.scapeType = .portrait
    let resetOrientationTargert = NSNumber(integerLiteral: UIInterfaceOrientation.unknown.rawValue)
    UIDevice.current.setValue(resetOrientationTargert, forKey: "orientation")
    
    let orientationTarget = NSNumber(integerLiteral: UIInterfaceOrientation.portrait.rawValue)
    UIDevice.current.setValue(orientationTarget, forKey: "orientation")
}

func transformDeviceOrientation(fullScreen: Bool) {
    guard #available(iOS 16.0, *) else {
        if fullScreen {
            NotificationCenter.default.post(name: DeviceDirectionLandscapeScreenNotice, object: nil)
            UIDevice.current.setValue(NSNumber.init(value: UIInterfaceOrientation.unknown.rawValue), forKey: "orientation")
            UIDevice.current.setValue(NSNumber.init(value: UIInterfaceOrientation.landscapeRight.rawValue), forKey: "orientation")
        } else {
            NotificationCenter.default.post(name: DeviceDirectionPortraitScreenNotice, object: nil)
            UIDevice.current.setValue(NSNumber.init(value: UIInterfaceOrientation.unknown.rawValue), forKey: "orientation")
            UIDevice.current.setValue(NSNumber.init(value: UIInterfaceOrientation.portrait.rawValue), forKey: "orientation")
        }
        return
    }
    switchMode(full: fullScreen)
    
}

private func switchMode(full: Bool) {
    DispatchQueue.main.async {
        guard
            let scence = UIApplication.shared.connectedScenes.first as? UIWindowScene
        else {
            return
        }
        if full{
            NotificationCenter.default.post(name: DeviceDirectionLandscapeScreenNotice, object: nil)
        }else{
            NotificationCenter.default.post(name: DeviceDirectionPortraitScreenNotice, object: nil)
        }
        
        
        let orientation: UIInterfaceOrientationMask = full ? .landscapeRight : .portrait
        if #available(iOS 16.0, *) {
            if let window = UIApplication.shared.currentWindow,let controller = window.visibleViewController() {
                controller.setNeedsUpdateOfSupportedInterfaceOrientations()
            }
            let geometryPreferencesIOS = UIWindowScene.GeometryPreferences.iOS(interfaceOrientations: orientation)
            scence.requestGeometryUpdate(geometryPreferencesIOS) { error in
                print("debug \(error)")
            }
        } else {
            // Fallback on earlier versions
            UIViewController.attemptRotationToDeviceOrientation()
        }
    }
}



extension String{
    func paddingImageUrl()->String{
        if self.contains("http"){
            return self
        }
        return productionUrl + self
    }
}

import Kingfisher
extension UIImageView{
    func loadImageWithUrl(_ url: String,_ success: ((_ image: UIImage)->Void)? = nil,_ failed: (()->Void)? = nil){
        if  url.isEmpty == false,let imageUrl = URL.init(string: url.paddingImageUrl()) {
            let resource  = KF.ImageResource.init(downloadURL: imageUrl)
            let cache     = KingfisherManager.shared.cache
            let optionsInfo = [KingfisherOptionsInfoItem.transition(ImageTransition.fade(1)),
                               KingfisherOptionsInfoItem.targetCache(cache)]
            self.kf.setImage(with: resource,
                             placeholder: nil,
                             options: optionsInfo,
                             progressBlock: nil) { result in
                switch result {
                case .success(let imageData):
                    if let block = success {
                        block(imageData.image)
                    }
                    break
                case .failure:
                    if let block = failed {
                        block()
                    }
                    break
                }
            }
        }else{
            self.image = nil
            if let block = failed {
                block()
            }
        }
    }
}

func randomString() -> String {
    let characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
    let length = 5
    var randomString = ""
    for _ in 0..<length {
        let randomIndex = Int(arc4random_uniform(UInt32(characters.count)))
        let randomCharacter = characters[characters.index(characters.startIndex, offsetBy: randomIndex)]
        randomString += String(randomCharacter)
    }
    return randomString
}


